// 立即执行函数 开发插件 选项卡

;(function (doc, tpl, tools) {

  // console.log(tpl, tools)

  function MyTab(el) {
    this.el = doc.querySelector(el);
    this.data = JSON.parse(this.el.getAttribute('data') || '[]');
    this._index = 0;
    // console.log(this.data);

    this.init();
  }
  // 启动
  MyTab.prototype.init = function() {
    this._render(); // 渲染
    this._bindEvent(); // 绑定事件处理函数
  }

  MyTab.prototype._render = function() {
    var tabWrapper = doc.createElement('div');
    var pageWrapper = doc.createElement('div');
    var oFrag = doc.createDocumentFragment(); // 创建文档碎片

    tabWrapper.className = 'tab-wrapper';
    pageWrapper.className = 'page-wrapper';

    this.data.forEach(function(item, index) {
      tabWrapper.innerHTML += tools.tplReplace(tpl.tab('tab'), {
        tab: item.tab,
        current: !index ? 'current': '' // 第一项才加 current 类名
      })

      pageWrapper.innerHTML += tools.tplReplace(tpl.tab('page'), {
        page: item.page,
        current: !index ? 'current': ''
      })
    })
    console.log(tabWrapper, pageWrapper);

    oFrag.appendChild(tabWrapper);
    oFrag.appendChild(pageWrapper);

    this.el.appendChild(oFrag); // 真实节点只操作一次
  }

  MyTab.prototype._bindEvent = function() {

    var doms = {
      oTabItems: doc.querySelectorAll('.tab-item'),
      oPageItems: doc.querySelectorAll('.page-item')
    }

    this.el.addEventListener('click', this._handleTabClick.bind(this, doms), false);
  }

  MyTab.prototype._handleTabClick = function() {
    console.log(arguments);
    var _doms = arguments[0],
        tar = arguments[1].target,
        className = tar.className.trim();

    if (className === 'tab-item') {
      _doms.oTabItems[this._index].className = 'tab-item';
      _doms.oPageItems[this._index].className = 'page-item';

      // 避免出现问题，使用数组的原生方法 重新找点击的tab 下标
      this._index = [].indexOf.call(_doms.oTabItems, tar);
      // console.log(this._index);

      tar.className += ' current';
      _doms.oPageItems[this._index].className += ' current';
    }

  }

  window.MyTab = MyTab
})(document, tpl, tools);



